package site.hugboy.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import site.hugboy.reggie.common.MyException;
import site.hugboy.reggie.entity.Category;
import site.hugboy.reggie.entity.Dish;
import site.hugboy.reggie.entity.Setmeal;
import site.hugboy.reggie.mapper.CategoryMapper;
import site.hugboy.reggie.service.CategoryService;
import site.hugboy.reggie.service.DishService;
import site.hugboy.reggie.service.SetmealService;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService ds;

    @Autowired
    private SetmealService ss;


    /**
     * 根据 id 删除分类前， 查询是否有关联 菜品/套餐
     * 是：抛出异常
     * 否：正常删除
     *
     * @param id
     */
    @Override
    public void remove(Long id) {
        LambdaQueryWrapper<Dish> Dqw = new LambdaQueryWrapper<>();
        // 配置查询条件: 根据分类id查询
        Dqw.eq(Dish::getCategoryId, id);
        int count = ds.count(Dqw);
        // 查询当前分类是否关联了菜品
        if (count > 0) {
            // 关联了菜品，抛出一个业务异常
            throw new MyException("分类关联了菜品，不可删除.");
        }

        // 类似的，校验是否关联 套餐
        LambdaQueryWrapper<Setmeal> Sqw = new LambdaQueryWrapper<>();
        Sqw.eq(Setmeal::getCategoryId, id);
        int count_2 = ss.count(Sqw);
        if(count_2 > 0){
            // 关联了套餐，抛出一个业务异常
            throw new MyException("分类关联了套餐，不可删除.");
        }
        // 正常删除分类
        super.removeById(id);
    }
}
